package mspbots.autotask.data.core.surveyresults;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import mspbots.autotask.data.core.AbstractToolsUtil;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class SurveyResultsReceiver extends AbstractToolsUtil {

    private final SurveyResultsRepository surveyResultRepository;

    @RabbitListener(queues = "auto-task.survey-results.sync")
    public void syncTask(ResultMsg content) {
        SurveyResult surveyResult = SurveyResult.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(surveyResult.getOtherId())) {
            return;
        }

        this.surveyResultRepository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(ticket -> {
                    surveyResult.setId(ticket.getId());
                    return surveyResult;

                })
                .defaultIfEmpty(surveyResult)
                .flatMap(this.surveyResultRepository::save)
                .block(Duration.ofSeconds(10));

    }
}
